package com.origin.app.page.company_list.adapter

import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import com.origin.app.MyApplication
import com.origin.app.R
import com.origin.app.bean.CompanyBean
import com.origin.app.databinding.ItemCompanyBinding
import com.origin.app.dialog.CompanyListDialog
import com.origin.app.page.map.AppMapViewModel
import com.origin.uilibrary.xbanner.XBannerUtils
import com.origin.uilibrary.xrecycleview.adapter.BaseRecycleAdapter
import com.origin.uilibrary.xrecycleview.viewholder.BaseViewHolder
import com.origin.utils.log.LogUtils
import com.origin.utils.screen.ScreenUtils

class CompanyAdapter(list: MutableList<CompanyBean>, context: Context) :
    BaseRecycleAdapter<CompanyBean>(list, context) {
    override fun setItemData(holder: BaseViewHolder, item: CompanyBean, position: Int) {
        var itemCompanyBinding = holder.binding as ItemCompanyBinding
        itemCompanyBinding.companyBean = item;
        itemCompanyBinding.root.setOnClickListener {
            expandOrClose(position, item)
        }
        itemCompanyBinding.ivSelect.setOnClickListener {
            if (CompanyListDialog.isMultiple) {
                selectOrClose(item)
                if(changeNumber==0){
                    changeNumber=1
                }
                notifyItemRangeChanged(position, changeNumber)
            } else {
                item.isSelect = !item.isSelect
                notifyItemChanged(position)
            }
        }
        item.isOpen = !closeItemList.contains(item.id)
        if (item.isParentLevel(closeItemList)) {
            itemCompanyBinding.root.layoutParams.height = 0;
        } else {
            itemCompanyBinding.root.layoutParams.height =
                XBannerUtils.dp2px(MyApplication.getInstance(), 50 * 1.0f)
        }
    }

    var changeNumber: Int = 0;
    private fun selectOrClose(item: CompanyBean) {
        changeNumber = 0;
        item.isSelect = !item.isSelect
        selectOrCloseNext(item, item.isSelect)
    }

    private fun selectOrCloseNext(item: CompanyBean, isSelect: Boolean) {
        item.companyBeanList.forEach {
            changeNumber++
            it.isSelect = isSelect;
            selectOrCloseNext(it, isSelect)
        }
    }


    val closeItemList = mutableListOf<Int>()
    fun expandOrClose(positionStart: Int, companyBean: CompanyBean) {
        if (closeItemList.contains(companyBean.id)) {
            closeItemList.remove(companyBean.id)
        } else {
            closeItemList.add(companyBean.id)
        }
        notifyItemRangeChanged(positionStart, companyBean.nextSize + 1)
    }

    override fun getViewResource(
        inflater: LayoutInflater,
        viewType: Int,
        parent: ViewGroup
    ): BaseViewHolder {
        return loadDataBindingBaseViewHolder<ItemCompanyBinding>(
            inflater,
            parent,
            R.layout.item_company
        )
    }
}